import type {
  SuanzhuGatewayResponse,
  ApiResponse,
  StatusFormat,
  StatusEnum,
  AppTypeEnum,
  ConnectModeEnum,
  ProviderTypeEnum
} from '../types'
import { createMockData, mockDelay, createMockError } from '../mock/data'

/**
 * 算珠网关API服务
 */
class SuanzhuApiService {
  private baseUrl = '/api/suanzhu'

  /**
   * 获取算珠网关二维码信息
   */
  async getQrcodeInfo(qrcode: string, useMock = false): Promise<SuanzhuGatewayResponse> {
    if (useMock) {
      await mockDelay(800)

      // 10% 概率返回错误
      if (Math.random() < 0.1) {
        return createMockError(qrcode)
      }

      return createMockData(qrcode)
    }

    try {
      const response = await fetch(`${this.baseUrl}/qrcode/entry?qrcode=${encodeURIComponent(qrcode)}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result: ApiResponse<SuanzhuGatewayResponse> = await response.json()

      if (!result.success) {
        throw new Error(result.message || '获取数据失败')
      }

      return result.data || { error: '数据为空' }
    } catch (error) {
      console.error('获取算珠网关信息失败:', error)
      return {
        error: error instanceof Error ? error.message : '网络请求失败'
      }
    }
  }
}

/**
 * 格式化状态
 */
export const formatStatus = (status: StatusEnum): StatusFormat => {
  switch (status) {
    case StatusEnum.ENABLED:
      return { text: '启用', color: 'success' }
    case StatusEnum.DISABLED:
      return { text: '禁用', color: 'error' }
    default:
      return { text: '未知', color: 'default' }
  }
}

/**
 * 格式化应用类型
 */
export const formatAppType = (appType: AppTypeEnum): string => {
  switch (appType) {
    case AppTypeEnum.WEB:
      return 'Web应用'
    case AppTypeEnum.MOBILE:
      return '移动应用'
    case AppTypeEnum.MINI_PROGRAM:
      return '小程序'
    default:
      return '未知类型'
  }
}

/**
 * 格式化连接模式
 */
export const formatConnectMode = (connectMode: ConnectModeEnum): string => {
  switch (connectMode) {
    case ConnectModeEnum.DIRECT:
      return '直连模式'
    case ConnectModeEnum.PROXY:
      return '代理模式'
    default:
      return '未知模式'
  }
}

/**
 * 格式化服务商类型
 */
export const formatProviderType = (providerType: ProviderTypeEnum): string => {
  switch (providerType) {
    case ProviderTypeEnum.PLATFORM:
      return '平台服务商'
    case ProviderTypeEnum.THIRD_PARTY:
      return '第三方服务商'
    default:
      return '未知类型'
  }
}

// 导出API服务实例
export const suanzhuApi = new SuanzhuApiService()

// 导出类型
export type { SuanzhuGatewayResponse, StatusFormat }